//
//  YCDynamicNavigationBar.m
//  YCDynamicNavigationBarDemo
//
//  Created by Jim on 2018/8/13.
//  Copyright © 2018年 youcash. All rights reserved.
//

#import "YCDynamicNavigationBar.h"

#define kIphoneX (([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125,2436), [[UIScreen mainScreen] currentMode].size) : NO))

static const CGFloat kMinTitleFontSize = 13;

@interface YCDynamicNavigationBar () {
    CGRect _originalRect; // 初始rect
    CGFloat _statusHeight; // 状态栏高度
    CGFloat minBarHeight; // 最小高度
}

@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UILabel *titleLb;
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) UIView *bottomLine;
@property (nonatomic, weak) UIScrollView *scrollView; // 绑定的scrollView

@end

@implementation YCDynamicNavigationBar

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _originalRect = frame;
        _statusHeight = kIphoneX ? 44 : 20;
        minBarHeight = kIphoneX ? 64 : 40;
        _resetHeight = 40;
        _originalTitleFont = [UIFont boldSystemFontOfSize:17];
        
        self.backgroundColor = [UIColor clearColor];
        [self addSubview:self.backgroundView];
        [self addSubview:self.titleLb];
        [self addSubview:self.bottomLine];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.backgroundView.frame = self.bounds;
    
    CGFloat width = CGRectGetWidth(self.frame);
    CGFloat height = CGRectGetHeight(self.frame);
    
    [self bringSubviewToFront:self.bottomLine];
    self.bottomLine.frame = CGRectMake(0, height - 0.5, width, 0.5);
    
    self.titleLb.frame = CGRectMake(50, _statusHeight, width - 100, height - _statusHeight);
    CGFloat fontSize = self.originalTitleFont.pointSize * height / _originalRect.size.height;
    fontSize = MAX(kMinTitleFontSize, fontSize);
    self.titleLb.font = [self.originalTitleFont fontWithSize:fontSize];
    
    CGFloat alpha = 1 - (_originalRect.size.height - height) / 2;
    self.leftBtn.alpha = alpha;
    self.rightBtn.alpha = alpha;
}

- (void)dealloc {
    [_scrollView removeObserver:self forKeyPath:@"contentOffset"];
}


#pragma mark - Public

- (void)addLeftTitle:(NSString *)title image:(UIImage *)image target:(id)target action:(SEL)action {
    if (self.leftBtn) [self.leftBtn removeFromSuperview];
    
    self.leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.leftBtn.frame = CGRectMake(0, _statusHeight, 44, 44);
    [self.leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.leftBtn setTitle:title forState:UIControlStateNormal];
    [self.leftBtn setImage:image forState:UIControlStateNormal];
    [self.leftBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.leftBtn];
}

- (void)addRightTitle:(NSString *)title image:(UIImage *)image target:(id)target action:(SEL)action {
    if (self.rightBtn) [self.rightBtn removeFromSuperview];
    
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn.frame = CGRectMake(CGRectGetWidth(self.frame) - 44, _statusHeight, 44, 44);
    [self.rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.rightBtn setTitle:title forState:UIControlStateNormal];
    [self.rightBtn setImage:image forState:UIControlStateNormal];
    [self.rightBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.rightBtn];
}

- (void)bindScrollView:(UIScrollView *)scrollView {
    if (self.scrollView) {
        [self.scrollView removeObserver:self forKeyPath:@"contentOffset"];
    }
    self.scrollView = scrollView;
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGFloat oldOffsetV = [(NSValue *)change[NSKeyValueChangeOldKey] UIOffsetValue].vertical;
        CGFloat newOffsetV = [(NSValue *)change[NSKeyValueChangeNewKey] UIOffsetValue].vertical;
        
        NSLog(@"newOffsetV: %f, delta offsetV: %f", newOffsetV, newOffsetV - oldOffsetV);
        
        if (newOffsetV == oldOffsetV || oldOffsetV < 0 || newOffsetV < 0) {
            return;
        }
        CGFloat maxScroll = self.scrollView.contentSize.height - self.scrollView.frame.size.height + self.scrollView.contentInset.bottom;
        if (oldOffsetV > maxScroll || newOffsetV > maxScroll) {
            return;
        }
        
        static BOOL upScroll = NO;
        static BOOL downScroll = NO;
        static CGFloat tempOffsetV = 0;
        
        if (newOffsetV > oldOffsetV) { // 上滑
            if (newOffsetV < self.threshold) {
                return;
            }
            
            downScroll = NO;
            if (!upScroll) {
                tempOffsetV = oldOffsetV;
                upScroll = YES;
            }
            
            CGFloat barHeight = _originalRect.size.height - (newOffsetV - tempOffsetV);
            barHeight = MAX(minBarHeight, barHeight);
            
            CGRect rect = _originalRect;
            rect.size.height = barHeight;
            self.frame = rect;
            
            if ([self.delegate respondsToSelector:@selector(dynamicBar:didChangeHeight:)]) {
                [self.delegate dynamicBar:self didChangeHeight:barHeight];
            }
            
        } else if (newOffsetV < oldOffsetV) { // 下滑
            upScroll = NO;
            if (!downScroll) {
                tempOffsetV = oldOffsetV;
                downScroll = YES;
            }
            
            CGFloat deltaHeight = tempOffsetV - newOffsetV;
            if (deltaHeight < _resetHeight) {
                return;
            }
            
            CGFloat barHeight = self.frame.size.height + (deltaHeight - _resetHeight);
            barHeight = MIN(_originalRect.size.height, barHeight);
            
            CGRect rect = _originalRect;
            rect.size.height = barHeight;
            self.frame = rect;
            
            if ([self.delegate respondsToSelector:@selector(dynamicBar:didChangeHeight:)]) {
                [self.delegate dynamicBar:self didChangeHeight:barHeight];
            }
        }
    }
}

#pragma mark - Setter & Getter

- (void)setOriginalTitleFont:(UIFont *)originalTitleFont {
    _originalTitleFont = originalTitleFont;
    self.titleLb.font = originalTitleFont;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor {
    self.backgroundView.backgroundColor = backgroundColor;
}

- (void)setHideBottomLine:(BOOL)hideBottomLine {
    _hideBottomLine = hideBottomLine;
    self.bottomLine.hidden = hideBottomLine;
}

- (UILabel *)titleLb {
    if (_titleLb == nil) {
        _titleLb = [[UILabel alloc] init];
        _titleLb.font = self.originalTitleFont;
        _titleLb.textAlignment = NSTextAlignmentCenter;
        _titleLb.text = @"";
    }
    return _titleLb;
}

- (UIView *)backgroundView {
    if (_backgroundView == nil) {
        _backgroundView = [[UIView alloc] initWithFrame:self.bounds];
        _backgroundView.backgroundColor = [UIColor whiteColor];
    }
    return _backgroundView;
}

- (UIView *)bottomLine {
    if (_bottomLine == nil) {
        _bottomLine = [[UIView alloc] initWithFrame:CGRectZero];
        _bottomLine.backgroundColor = [UIColor colorWithRed:167.0/255.0 green:167.0/255.0 blue:172.0/255.0 alpha:1.0];
        _bottomLine.userInteractionEnabled = NO;
    }
    return _bottomLine;
}

@end
